package com.cruise.game.service.impl.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.common.enums.UserStatusEnum;
import com.cruise.game.mapper.OrderMapper;
import com.cruise.game.mapper.TransactionMapper;
import com.cruise.game.mapper.UserMapper;
import com.cruise.game.model.entity.User;
import com.cruise.game.model.param.admin.UserStatusParam;
import com.cruise.game.model.vo.admin.UserDetailVO;
import com.cruise.game.model.vo.admin.UserListVO;
import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.service.admin.AdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理员用户服务实现
 * 
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private TransactionMapper transactionMapper;

    @Override
    public PageResult<UserListVO> getUserList(String role, String status, String keyword, Integer page, Integer pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(role)) {
            queryWrapper.eq(User::getRole, role);
        }
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(User::getStatus, status);
        }
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                    .like(User::getNickname, keyword)
                    .or()
                    .like(User::getPhone, keyword)
                    .or()
                    .like(User::getWechatId, keyword)
            );
        }
        
        // 分页查询
        IPage<User> userPage = userMapper.selectPage(new Page<>(page, pageSize), queryWrapper);
        
        // 转换为VO
        List<UserListVO> userListVOs = new ArrayList<>();
        for (User user : userPage.getRecords()) {
            UserListVO vo = new UserListVO();
            BeanUtils.copyProperties(user, vo);
            vo.setAvatar(user.getAvatarUrl());
            userListVOs.add(vo);
        }
        
        // 构建分页结果
        return PageResult.of(userListVOs, userPage.getTotal(), page, pageSize);
    }

    @Override
    public UserDetailVO getUserDetail(Long userId) {
        // 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ApiException("用户不存在");
        }
        
        // 构建用户详情VO
        UserDetailVO userDetailVO = new UserDetailVO();
        BeanUtils.copyProperties(user, userDetailVO);
        userDetailVO.setAvatar(user.getAvatarUrl());
        
        // 构建订单统计
        UserDetailVO.OrderStats orderStats = new UserDetailVO.OrderStats();
        orderStats.setTotalOrders(orderMapper.countByUserId(userId, null));
        orderStats.setCompletedOrders(orderMapper.countByUserId(userId, "completed"));
        orderStats.setCancelledOrders(orderMapper.countByUserId(userId, "cancelled"));
        userDetailVO.setOrderStats(orderStats);
        
        // 构建余额统计
        UserDetailVO.BalanceStats balanceStats = new UserDetailVO.BalanceStats();
        BigDecimal totalRecharge = transactionMapper.sumUserRechargeAmount(userId);
        BigDecimal totalSpent = transactionMapper.sumUserPaymentAmount(userId);
        balanceStats.setTotalRecharge(totalRecharge != null ? totalRecharge : BigDecimal.ZERO);
        balanceStats.setTotalSpent(totalSpent != null ? totalSpent : BigDecimal.ZERO);
        userDetailVO.setBalanceStats(balanceStats);
        
        return userDetailVO;
    }

    @Override
    public boolean updateUserStatus(Long userId, UserStatusParam param) {
        // 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ApiException("用户不存在");
        }
        
        // 验证状态
        String status = param.getStatus();
        UserStatusEnum statusEnum = UserStatusEnum.getByValue(status);
        if (statusEnum == null) {
            throw new ApiException("无效的状态");
        }
        
        // 更新状态
        return userMapper.updateStatus(userId, status) > 0;
    }
}
